#! /usr/bin/env python

import difflib
import os
"""
这个Python脚本定义了两个类：

DiffString类用于比较两个字符串的差异，通过split方法按行分割后，使用difflib库进行逐行对比。若无差异则返回'no diff'，否则打印并返回'diff'。

DiffFile类用于比较两个文件的差异，通过readFile方法读取文件内容，然后使用difflib库生成HTML形式的差异报告，并保存为diff.html文件。最后返回提示信息"html file is diff.html"。
"""
class DiffString:
    def __init__(self,str1,str2):
        self.str1 = str1
        self.str2 = str2
    def diff(self):
        str1_lines = self.str1.split('\n')
        str2_lines = self.str2.split('\n')
        diff1 = difflib.Differ()
        str3 = diff1.compare(str1_lines,str2_lines)
        str3 = list(str3)
        if  len(str3) == 1:
            return 'no diff'
        else:
            print('\n'.join(str3))
            return 'diff'
class DiffFile:
    def __init__(self,file1,file2):
        self.file1 = file1
        self.file2 = file2
    def readFile(self,filename):
        name = os.path.dirname(os.path.abspath(__file__))
        filehandle = os.path.join(name,filename)
        with open(filehandle,'r') as f:
            text = f.read().split('\n')
        return text
        
    def diffFile(self):
        file1 = self.readFile(self.file1)
        file2 = self.readFile(self.file2)
        diff1 = difflib.HtmlDiff()
        file3 = diff1.make_file(file1,file2)
        with open('diff.html','w') as f:
            f.write(file3)
        return f"html file is diff.html"
if __name__ == '__main__':
    text = DiffString('hello world hahaha','hello world')
    print(text.diff())
    file1 = "1.txt"
    file2 = "2.txt"
    textFile = DiffFile(file1,file2)
    print(textFile.diffFile())